<?php

namespace app\admin\controller\qingdongwms\customer;

use addons\qingdongwms\model\ContractProduct;
use addons\qingdongwms\model\CustomerOther;
use addons\qingdongwms\model\DeliveryProduct;
use addons\qingdongwms\model\ExamineRecord;
use addons\qingdongwms\model\Contract;
use addons\qingdongwms\model\FormField;
use addons\qingdongwms\model\ProductPart;
use addons\qingdongwms\model\Product;
use addons\qingdongwms\model\Ratio;
use addons\qingdongwms\model\Staff;
use addons\qingdongwms\model\Warehouse;
use app\admin\controller\qingdongwms\Base;
use addons\qingdongwms\model\DeliveryOther;
use addons\qingdongwms\model\Form;
use addons\qingdongwms\model\Contacts;
use addons\qingdongwms\model\Customer;
use addons\qingdongwms\model\OperationLog;
use addons\qingdongwms\model\Record;
use addons\qingdongwms\model\ContractFile;
use addons\qingdongwms\model\Flow;
use addons\qingdongwms\model\Message;
use think\Db;
use think\Exception;


/**
 * 发货单
 * @icon fa fa-sign-out
 */
class Delivery extends Base {
    protected $relationSearch = true;
    /**
     * @var \addons\qingdongwms\model\Delivery
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \addons\qingdongwms\model\Delivery;
    }


    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',0);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            switch($type){
                case 1:
                    $staff = Staff::info();
                    $wheres['owner_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['owner_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['owner_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $ids=[];
            $group_id=input('group_id');
            $staff_id=input('staff_id');
            if ($group_id) {//角色组
                $ids = Staff::getGroupStaffIds($group_id);
            }
            if ($staff_id) {
                $ids = $staff_id;
            }
            if ($group_id || $staff_id) {
                $wheres['owner_staff_id'] = ['in', $ids];
            }
            $list = $this->model->where($where)
                ->where($wheres)
                ->with([
                    'customer',
                    'contacts',
                    'warehouse',
                ])->order($sort, $order)->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $field = FormField::getFields(FormField::DELIVERY_TYPE);
        $this->assignconfig('fields', $field);

        return $this->view->fetch();
    }


    /**
     * 添加发货单
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                // 表单验证
                if (($result = $this->qingdongwmsValidate($params, 'Delivery', 'create')) !== true) {
                    $this->error($result);
                }
                if (isset($params['num'])) {
                    if (empty($params['num'])) {
                        $params['num'] = $this->model::getNum();
                    }
                    $delivery = $this->model::where(['num' => $params['num']])->find();
                    if ($delivery) {
                        $this->error('发货单编号已存在');
                    }
                } else {
                    $params['num'] = $this->model::getNum();
                }
                if(isset($params['flow_staff_ids'])){
                    if(!$params['flow_staff_ids']){
                        $this->error('请选择审批人');
                    }
                }
                $result = false;
                $result = FormField::checkFields(FormField::DELIVERY_TYPE, $params);
                if ($result !== true) {
                    $this->error($result);
                }
                Db::startTrans();
                try {
                    $params=Form::updateFormParams('delivery',$params);
                    if($params['product']){
                        $params['product']=json_decode($params['product'],true);
                    }
                    $result = $this->model::createDelivery($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $flow= Flow::getsteplist(Flow::DELIVERY_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员','qingdongwms/work/flow');
        }
        $customer_id = input('customer_id');
        $contract_id = input('contract_id');
        $this->assign('customer_id', input('customer_id'));
        $this->assign('contract_id', input('contract_id'));
        $this->assign('flow',$flow);
        $this->assign('staff', Staff::getStaff());
        $this->assign('customers', Customer::getList());
        $this->assign('staffs',     Staff::allList());
        $this->assign('form_data', Form::getDataValue('delivery'));
        $this->assign('customer', Customer::get($customer_id));
        $this->assign('contract', Contract::get($contract_id));
        $this->assign('ratio',Ratio::where(['status'=>1])->select());
        return $this->view->fetch();
    }


    /**
     * 销售单转为发货单
     */
    public function convert()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                // 表单验证
                if (($result = $this->qingdongwmsValidate($params, 'Delivery', 'create')) !== true) {
                    $this->error($result);
                }
                if (isset($params['num'])) {
                    if (empty($params['num'])) {
                        $params['num'] = $this->model::getNum();
                    }
                    $delivery = $this->model::where(['num' => $params['num']])->find();
                    if ($delivery) {
                        $this->error('发货单编号已存在');
                    }
                } else {
                    $params['num'] = $this->model::getNum();
                }
                $result = false;
                $result = FormField::checkFields(FormField::DELIVERY_TYPE, $params);
                if ($result !== true) {
                    $this->error($result);
                }
                Db::startTrans();
                try {
                    $params=Form::updateFormParams('delivery',$params);
                    if($params['product']){
                        $params['product']=json_decode($params['product'],true);
                    }
                    $result = $this->model::createDelivery($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $flow= Flow::getsteplist(Flow::DELIVERY_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员','qingdongwms/work/flow');
        }
        $contract_id = input('contract_id');
        $contract = Contract::where(['id' => $contract_id])->find();
        if (empty($contract)) {
            $this->error('参数错误');
        }
        if($contract['ship_status'] ==1){
            $this->error('当前销售单已发货，无法重复转为发货单');
        }
        $this->assign('row', $contract);

        $this->assign('flow',$flow);
        $this->assign('staff', Staff::getStaff());
        $this->assign('customers', Customer::getList());
        $this->assign('staffs',     Staff::allList());
        $this->assign('form_data', Form::getDataValue('delivery'));
        $this->assign('ratio',Ratio::where(['status'=>1])->select());
        return $this->view->fetch();
    }



    /**
     * 修改发货单
     * @param null $ids
     * @return string
     */
    public function edit($ids = null) {
        $map['id'] = $ids;
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params = $this->preExcludeFields($params);
            $row = $this->model::where(['id' => $ids, 'check_status' => ['in', [3, 4]]])->find();
            if (empty($row)) {
                $this->error('发货单审核中或已审核通过无法修改');
            }
            // 表单验证
            if (($result = $this->qingdongwmsValidate($params, 'Delivery', 'create')) !== true) {
                $this->error($result);
            }
            $result = FormField::checkFields(FormField::DELIVERY_TYPE, $params,$ids);
            if ($result !== true) {
                $this->error($result);
            }
            Db::startTrans();
            try {
                if($params['product']){
                    $params['product']=json_decode($params['product'],true);
                }
                $params=Form::updateFormParams('delivery',$params);
                $params['id']=$ids;
                $result = $this->model::updateDelivery($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('修改成功');
        }
        $row = $this->model->where($map)->with(['customer','contract'])->find();

        $row = $row->toArray();
        $row = DeliveryOther::getOther($row);
        $flow= Flow::getsteplist(Flow::DELIVERY_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员');
        }
        $product = DeliveryProduct::where(array('delivery_id'=>$ids))->select();
        $row['product'] = json_encode($product);
        $this->assign('flow',$flow);
        $this->view->assign("row", $row);
        $this->assign('contacts', Contacts::where(['customer_id'=>$row['customer_id']])->field('id,name')->select());
        $this->assign('customers', Customer::getList());
        $this->assign('staff', Staff::getStaff());
        $this->assign('ratio',Ratio::where(['status'=>1])->select());
        $this->assign('form_data', Form::getDataValue('delivery',$row));

        return $this->view->fetch();
    }


    /**
     * 获取附件记录
     * @param null $ids
     */
    public function get_file($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = ContractFile::where(['contract_id' => $ids])->with(['file'])->field('file_id')->paginate($limit);

        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

    /**
     * 报价单详情
     * @param null $ids
     * @return string
     */
    public function detail($ids = null) {
        $row = $this->model::withTrashed()->where(['id' => $ids])->with([
            'customer',
            'contacts',
            'ownerStaff'
        ])->find();
        if (empty($row)) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $row=DeliveryOther::getOther($row);



        $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::CONTRACT_TYPE,$ids));

        $this->assign('flow',Flow::getstepdetail(Flow::DELIVERY_STATUS, $ids));
        //操作记录
        $log=OperationLog::getList(OperationLog::DELIVERY_TYPE, $ids);
        //标记通知已读
        Message::setRead(Message::DELIVERY_TYPE, $ids, $this->_staff->id);
        $this->assign('operation_log',$log);
        $this->assign('row', $row);
        $this->assign('ids', $ids);
        $this->assign('form_data', Form::getDataValue('delivery',$row));
        $this->assignconfig("idinfo", ['id' => $ids]);
        return $this->view->fetch();
    }
    /**
     * 作废发货单
     * @param null $ids
     * @return string
     */
    public function revoke($ids=null){
        if ($this->request->isAjax()) {
            $remarks = input('remarks','');

            $row = $this->model->get($ids);
            if (empty($row)) {
                $this->error('信息不存在');
            }
            Db::startTrans();
            try{
                $result = $this->model->save(['delivery_status' => 2, 'check_status' => 9,'deletetime'=>time()], ['id' => $ids]);
                if (empty($result)) {
                    throw new Exception('修改失败');
                }
                $this->model::revoke($ids,$row['warehouse_id']);
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            OperationLog::createLog(OperationLog::DELIVERY_TYPE, $ids, '作废发货单，备注：' . $remarks);
            $this->success('作废成功');
        }
        return $this->view->fetch();
    }
    /**
     * 获取联系人select
     */
    public function get_contacts_list(){
        $customer_id=input('customer_id');
        if(empty($customer_id)){
            $this->error(__('Invalid parameters'));
        }
        $contacts=Contacts::where(['customer_id'=>$customer_id])->field('id,name')->select();
        $this->success('请求成功','',$contacts);
    }

    /**
     * 获取客户详情
     */
    public function get_customer_detail()
    {
        $id = input('customer_id');
        if (empty($id)) {
            $this->error(__('Invalid parameters'));
        }
        $row = Customer::get($id);
        $other = CustomerOther::getOther($id);
        $row = $row->toArray();
        $row = array_merge($row, $other);

        $this->success('请求成功', '', $row);
    }

    /**
     * 获取回款计划
     * @param null $ids
     * @return \think\response\Json
     */
    public function get_receivables_plan($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = \addons\qingdongwms\model\ReceivablesPlan::where([
            'contract_id' => $ids
        ])->with(['customer'])->paginate($limit);

        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

    /**
     * 获取销售单列表
     * @return \think\response\Json
     */
    public function get_contract(){
        $customer_id=input('ids');
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $where['customer_id']=$customer_id;
        $where['check_status']=2;
        $staff = Contract::where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }
    /**
     * 获取回款记录
     * @param null $ids
     * @return \think\response\Json
     */
    public function get_receivables($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = \addons\qingdongwms\model\Receivables::where([
            'contract_id' => $ids
        ])->with(['customer','ownerStaff'])->paginate($limit);

        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

    /**
     * 获取产品明细
     */
    public function get_contract_product(){
        $contract_id=input('contract_id',0,'intval');
        if(empty($contract_id)){
            $this->error('参数不能为空');
        }
        $products=ContractProduct::where(['contract_id'=>$contract_id,'ship_status'=>0])
            ->with(['product'])->select();
        $this->success('请求成功','',$products);
    }

    /**
     * 获取产品明细
     */
    public function get_delivery_product(){
        $delivery_id=input('delivery_id',0,'intval');
        if(empty($delivery_id)){
            $this->error('参数不能为空');
        }
        $products=DeliveryProduct::where(['delivery_id'=>$delivery_id])->with(['product'])->select();

        return json(['rows' =>$products, 'total' => count($products)]);
    }


    /**
     * 获取产品
     * @return \think\response\Json
     */
    public function get_product()
    {
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $where['status']='上架';
        $countrys = Product::where($where)->field('id,name')->order('id desc')->select();
        return json(['list' => $countrys, 'total' => count($countrys)]);
    }

    /**
     * 获取产品配置
     * @return \think\response\Json
     */
    public function get_product_part()
    {
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $countrys = ProductPart::where($where)->field('id,name')->order('id desc')->select();
        return json(['list' => $countrys, 'total' => count($countrys)]);
    }

    /**
     * 获取产品价格
     */
    public function get_product_price()
    {
        $id = input('id', 0);
        $product = Product::where(['id' => $id])->with(['goods'])->find();
        if(empty($product)){
            $this->error('参数错误');
        }
        $this->success('请求成功', '', $product);
    }


    /**
     * 获取审批人列表
     */
    public function getstaff(){
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $staff = Staff::where($where)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }
    /**
     * 获取仓库
     */
    public function getwarehouse(){
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $staff = Warehouse::where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }


    /**
     * 导出
     */
    public function export(){
        $ids=input('ids',0,'intval');
        if(empty($ids)){
            $this->error('参数错误');
        }
        $delivery=$this->model::where(['id'=>$ids])->with(['customer','contacts','product','staff','warehouse'])->find();
        if(empty($delivery)){
            $this->error('信息不存在');
        }
        $delivery=$delivery->toArray();
        $total_number=0;
        $total_price=0;
        foreach ($delivery['product'] as $v){
            if($delivery['online'] == '线下'){
                $v['price']=$v['wholesale'];
            }
            $total_number+=$v['number'];
            $total_price+=$v['price']*$v['number']+floatval($v['freight']);
        }
        //打印加1
        $this->model->where(['id' => $ids])->setInc('export_number');
        //已发货
        $this->model->where(['id' => $ids])->update(['delivery_status' => 1]);
        OperationLog::createLog(OperationLog::DELIVERY_TYPE, $ids, '打印发货单');

        $delivery['total_price']=$total_price;
        $delivery['total_number']=$total_number;

        $this->view->assign('row',$delivery);
        $this->view->assign('script','window.print();');
        $this->view->engine->layout(false);
       return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "") {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $map['id'] = array('in', $ids);
        $result = $this->model->destroy($map);
        if (!$result) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }
}
